<?php

namespace App\Models;

use Dcat\Admin\Traits\ModelTree;

use Illuminate\Database\Eloquent\Model;

class FhPage extends Model
{
	use ModelTree;
    protected $parentColumn = 'p_id';
    protected $table = 'fh_page';
    protected $titleColumn = 'name';
    protected $orderColumn = 'sort';

    public function getNav(){
        $data = $this->where("p_type",1)->where('show',1)->select('id','name','p_id','desc','url_type','sort','img','url')->get();
        // dd($this->getTree($data));
        return $this->getTree($data);
    }

    public function getSub(){
        $data = $this->where("p_type",2)->where('show',1)->select('id','name','p_id','desc','url_type','sort','img','url')->get();
        return $this->getTree($data);
    }


    protected function getTree($data,$parent = 0){
        $tree = [];
        $count = 0;
        foreach($data as $v){
            if($v->p_id==$parent){
                $v->img = empty($v->img)?"":env('APP_STATIC').$v->img;
                $tree[$count] = $v;
                $tree[$count]['sub']= $this->getTree($data,$v->id);
                $count++;
            }
        }
        $trees = json_encode($tree);
        $new_tree = json_decode($trees,true);
        $this->sortArray($new_tree);
        return $new_tree;
    }
    protected function sortArray(&$array){
        usort($array, function($a, $b) {
            return   $b['sort'] - $a['sort'];
        });
    
        foreach ($array as &$item) {
            if (isset($item['sub'])) {
                $this->sortArray($item['sub']);
            }
        }
    }
}